package com.example.test.advice.第五章_数组和集合.建议67_不同的列表选择不同的遍历方法;

import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * ArrayList 下标遍历更快
 */
public class ArrayListClient {

    public static void main(String[] args) {
        //学生数量80万
        int stuNum = 80*1000000;
        //List集合，记录所有分数
        List<Integer> scores = new ArrayList<Integer>(stuNum);

        //写入分数
        for(int i= 0;i< stuNum; i++){
            scores.add(new Random().nextInt(150));
        }
        //记录开始计算时间
        Instant start = Instant.now();
        System.out.println("平均分是："+average(scores));
        System.out.println("forEach执行时间："+ Duration.between(start,Instant.now()).toMillis());
        System.out.println();
        Instant second = Instant.now();
        System.out.println("平均分是："+average2(scores));
        System.out.println("下标遍历执行时间："+ Duration.between(second,Instant.now()).toMillis());
        System.out.println();
        Instant third = Instant.now();
        System.out.println("平均分是："+scores.stream().mapToInt(Integer::intValue).average().getAsDouble());
        System.out.println("JAVA8执行时间："+ Duration.between(third,Instant.now()).toMillis());
    }

    //计算平均分
    private static int  average(List<Integer> list){
        int sum = 0;
        for(int i :list){
            sum = sum+i;
        }
        return sum/list.size();
    }

    //计算平均分
    private static int  average2(List<Integer> list){
        int sum = 0;
        for(int i = 0;i<list.size(); i++){
            sum = sum+list.get(i);
        }
        return sum/list.size();
    }


}
